import json
import os
import time
import keyboard
import pyautogui
import win32gui
import win32api
import win32con
from threading import Thread, Event

class AutoClicker:
    def __init__(self):
        self.click_positions = []
        self.current_position_index = 0
        self.is_clicking = False
        self.stop_event = Event()
        self.click_interval = 1.0  # 默认点击间隔为1秒
        self.config_file = 'click_config.json'
        self.target_window = None  # 目标窗口句柄
        self.load_config()
        
    def load_config(self):
        if os.path.exists(self.config_file):
            try:
                with open(self.config_file, 'r') as f:
                    config = json.load(f)
                    self.click_positions = config.get('positions', [])
                    self.click_interval = config.get('interval', 1.0)
            except Exception as e:
                print(f'加载配置文件失败: {e}')
                self.create_default_config()
        else:
            self.create_default_config()
    
    def create_default_config(self):
        config = {
            'positions': [],
            'interval': 1.0
        }
        with open(self.config_file, 'w') as f:
            json.dump(config, f, indent=4)
    
    def save_config(self):
        config = {
            'positions': self.click_positions,
            'interval': self.click_interval
        }
        with open(self.config_file, 'w') as f:
            json.dump(config, f, indent=4)
    
    def add_click_position(self):
        if self.target_window:
            # 获取鼠标相对于窗口的位置
            cursor_pos = win32gui.GetCursorPos()
            window_rect = win32gui.GetWindowRect(self.target_window)
            relative_x = cursor_pos[0] - window_rect[0]
            relative_y = cursor_pos[1] - window_rect[1]
            self.click_positions.append({
                'x': relative_x,
                'y': relative_y,
                'window_handle': self.target_window
            })
            print(f'已添加窗口内点击位置: ({relative_x}, {relative_y})')
        else:
            current_pos = pyautogui.position()
            self.click_positions.append({'x': current_pos.x, 'y': current_pos.y})
            print(f'已添加屏幕点击位置: ({current_pos.x}, {current_pos.y})')
        self.save_config()
    
    def set_target_window(self):
        # 获取当前鼠标位置下的窗口句柄
        cursor_pos = win32gui.GetCursorPos()
        self.target_window = win32gui.WindowFromPoint(cursor_pos)
        if self.target_window:
            window_text = win32gui.GetWindowText(self.target_window)
            print(f'已设置目标窗口: {window_text} (句柄: {self.target_window})')
        else:
            print('未找到目标窗口')
    
    def next_position(self):
        if self.click_positions:
            self.current_position_index = (self.current_position_index + 1) % len(self.click_positions)
            pos = self.click_positions[self.current_position_index]
            print(f'切换到位置 {self.current_position_index + 1}: ({pos["x"]}, {pos["y"]})')
    
    def click_thread(self):
        while not self.stop_event.is_set():
            if self.is_clicking and self.click_positions:
                # 保存当前鼠标位置
                original_pos = pyautogui.position()
                
                # 执行点击
                pos = self.click_positions[self.current_position_index]
                if 'window_handle' in pos:
                    # 窗口内点击
                    try:
                        window_rect = win32gui.GetWindowRect(pos['window_handle'])
                        screen_x = window_rect[0] + pos['x']
                        screen_y = window_rect[1] + pos['y']
                        win32api.SetCursorPos((screen_x, screen_y))
                        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, 0, 0)
                        win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, 0, 0)
                    except Exception as e:
                        print(f'窗口点击失败: {e}')
                else:
                    # 屏幕坐标点击
                    pyautogui.click(pos['x'], pos['y'])
                
                # 恢复鼠标位置
                pyautogui.moveTo(original_pos.x, original_pos.y)
                
                time.sleep(self.click_interval)
            else:
                time.sleep(0.1)
    
    def toggle_clicking(self):
        if not self.click_positions:
            print('请先添加点击位置！')
            return
        
        self.is_clicking = not self.is_clicking
        print('点击状态:', '开启' if self.is_clicking else '关闭')
    
    def start(self):
        # 启动点击线程
        click_thread = Thread(target=self.click_thread)
        click_thread.daemon = True
        click_thread.start()
        
        # 注册热键
        keyboard.add_hotkey('ctrl+alt+s', self.toggle_clicking)
        keyboard.add_hotkey('ctrl+alt+p', self.add_click_position)
        keyboard.add_hotkey('ctrl+alt+n', self.next_position)
        keyboard.add_hotkey('ctrl+alt+w', self.set_target_window)
        
        print('后台点击工具已启动')
        print('热键说明：')
        print('Ctrl+Alt+S: 开始/停止点击')
        print('Ctrl+Alt+P: 设置当前鼠标位置为点击位置')
        print('Ctrl+Alt+N: 切换到下一个点击位置')
        print('Ctrl+Alt+W: 设置当前窗口为目标窗口')
        print('Ctrl+Alt+Q: 退出程序')
        
        # 等待退出热键
        keyboard.wait('ctrl+alt+q')
        self.stop_event.set()
        print('程序已退出')

if __name__ == '__main__':
    auto_clicker = AutoClicker()
    auto_clicker.start()